import { forwardRef, useImperativeHandle, useRef, useState } from "react";
import { DatePicker, message, Modal } from "antd";
import CourseCard from "./CourseCard";
import dayjs from "dayjs";
import weekOfYear from "dayjs/plugin/weekOfYear";
import { addClassCourseApi, updateClassCourseApi } from "@/api/school/class";
import { getGradeAndClassLabel } from "../../common";
import type { CourseType, ModalRefType } from "../types/editModalCard.type";
import type { CardRefType } from "../types/courseCard.type";

dayjs.extend(weekOfYear); // 借助 weekOfYear 插件解析 year-week

const EditModalCard = forwardRef<ModalRefType>((_, ref) => {
  const courseCardRef = useRef<CardRefType>(null);
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [messageApi, contextHolder] = message.useMessage();
  const [title, setTitle] = useState("");
  const [dateDefaultValue, setDateDefaultValue] = useState<dayjs.Dayjs>();
  const [details, setDetails] = useState<Partial<CourseType>>({});

  // * 暴露给父组件的属性, onOpen 是打开抽屉的方法
  useImperativeHandle(ref, () => ({
    onOpen: (record: any) => {
      init();
      const { course, gradeAndClass, subject } = record || {};
      const title = getGradeAndClassLabel(gradeAndClass);
      setTitle(`课程安排 ${title} ${subject === 0 ? "未分科" : subject === 1 ? "文科" : subject === 2 ? "理科" : ""}`);
      if (record?.id) {
        let { yearWeek } = course || {};
        if (yearWeek) {
          const [year, week] = yearWeek.split("-");
          yearWeek = dayjs().year(year).week(week.slice(0, -1));
        }
        setDateDefaultValue(yearWeek);
        setDetails(() => ({
          classId: record.id,
          yearWeek: course?.yearWeek,
          id: course?.id,
          details: course?.details,
        }));
      }
      setIsModalOpen(true);
    },
  }));

  const init = () => {
    setTitle("");
    setDateDefaultValue(undefined);
    setDetails({});
  };
  const handleOk = async () => {
    const courseData = courseCardRef.current?.onSubmit();
    const { classId, yearWeek, id } = details;
    const params = { classId, yearWeek, details: courseData };
    if (!yearWeek) return messageApi.error("请选择时间");
    if (id) {
      await updateClassCourseApi({ ...params, id });
    } else {
      await addClassCourseApi(params);
    }
    messageApi.success(id ? "编辑成功" : "新增成功");
    setTimeout(() => {
      handleCancel();
    }, 500);
  };
  const handleCancel = () => {
    setIsModalOpen(false);
  };
  const onPickerChange = (_: any, dateString: string | string[]) => {
    setDetails(prev => ({ ...prev, yearWeek: dateString as string }));
  };

  return (
    <>
      {contextHolder}
      <Modal
        className="!w-[50%] !min-w-800"
        title={
          <>
            {title}
            <DatePicker className="ml-8" picker="week" defaultValue={dateDefaultValue} onChange={onPickerChange} />
          </>
        }
        maskClosable={false}
        destroyOnClose={true}
        open={isModalOpen}
        onOk={handleOk}
        onCancel={handleCancel}
      >
        <CourseCard ref={courseCardRef} echoData={details.details}></CourseCard>
      </Modal>
    </>
  );
});

export default EditModalCard;
